<script lang="ts" setup>
import type { StateType } from './types';

import { computed } from 'vue';
import { useRoute } from 'vue-router';

import { Page ,z} from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import { $t } from '@vben/locales';
import { useTitle } from '@vueuse/core';
import {
  Card,
  message,
  Select,
  SelectOption,
  TabPane,
  Tabs,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';
import { pinyin } from 'pinyin-pro';

import { useVbenForm } from '#/adapter/form';
import { getPageInfo_news, postPage_news, putPage_news } from '#/api/portal/promotion';
import { usePreferencesStore } from '#/store';

import { useVbenModal } from '@vben/common-ui';


const index = ref<number>(0); // 外层定义
const [Modal, formModalApi] = useVbenModal({
  fullscreenButton: false,
  footer: false,
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values1: { id?: number } = formModalApi.getData();
      index.value = values1.id ?? 0; // 给外层的 index 赋值
      if(index.value>0){
             await onGetPage(index.value);
      }
      
    }
  },
 
});
const route = useRoute();

const { setTabTitle, closeCurrentTab } = useTabs();

// const index: any = computed(() => {
//   return route.params?.id ?? -1;
// });
const router = useRouter();

const routeMeta = router.currentRoute.value.meta;
const routeTitle = routeMeta.title.replace('管理', '');
const preferencesStore = usePreferencesStore();
const { title } = storeToRefs(preferencesStore);
// const pageTitle =
//   Number.parseInt(index.value, 10) === 0
//     ? $t('page.common.Add')+` ${routeTitle}`
//     : `No.${index.value} - `+$t('page.common.Edit')+` ${routeTitle}`;
// setTabTitle(pageTitle);
// useTitle(`${pageTitle} - ${title.value}`);

const disabled = ref(true);
const activeKey = ref('1');
const state: StateType = reactive({
  form: {
   

  },

});

const [BasicForm, BasicFormApi] = useVbenForm({
  handleSubmit: onSubmit,

  resetButtonOptions: {
    show: false,
  },
  commonConfig: {
    labelWidth: 200,
  },
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入(不能超过50字符)',
      },
      fieldName: 'name',
      label: `${routeTitle} `+$t('page.common.Attribute'),
      rules: z.string().max(50,'不能超过50字符'),
      
    },
    {
      component: 'Input',
      defaultValue: '',
      dependencies: {
        trigger: (values) => {
          disabled.value = !values.news_title;
          state.form.name = values.name;
          state.form.title = values.title;
          state.form.des = values.des;
          state.form.images = values.images;
          state.form.images = values.images;
          state.form.off = values.off;
          state.form.apr = values.apr;
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'id',
          'title',
          'name',
          'des',
          'images',
          'off',
          'apr',
        ],
      },
      componentProps: {
        placeholder: $t('page.common.Please Enter')+'('+$t('admin.maxChars', { length: 100 })+')',
      },
      fieldName: 'title',
      label: `${routeTitle} `+$t('page.common.Title'),
     rules: z.string().max(100,$t('admin.maxChars', { length: 100 })).optional(),
    },


    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'des',
      label: `${routeTitle} `+$t('page.common.Description'),
    },
     {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter')+'('+$t('admin.maxChars', { length: 20 })+')',
      },
      fieldName: 'off',
      label: `${routeTitle} `+$t('admin.discount'),
       rules: z.string().max(20,$t('admin.maxChars', { length: 20 })).optional(),
    },
     {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter')+'('+$t('admin.maxChars', { length: 50 })+')',
      },
      fieldName: 'apr',
      label: `${routeTitle} `+$t('admin.interestRate'),
      rules: z.string().max(20,$t('admin.maxChars', { length: 20 })).optional(),
    },

    {
      component: 'Upload',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'images',
      label: `${routeTitle} `+$t('admin.backgroundImage'),
      
    },

  ],
});



async function onSubmit() {
  function showMsg(msg: string) {
    message.success(msg);
    // closeCurrentTab();
    // console.log('可用路由:', router.getRoutes());

    //   router.push({
    //       name: `Portalpromotion`,
    //  });
    formModalApi.close();
    BasicFormApi.resetForm();
     state.form={};
  }
  const values: any = state.form;

  if (values.id) {
    const { msg } = await putPage_news(values);
    showMsg(msg);
  } else {
    delete values.id;
    const { msg } = await postPage_news(values);
    showMsg(msg);
  }
}
async function onGetPage(id: number) {
  const { data } = await getPageInfo_news({ id });
  data.post = {
    id: data?.id ?? undefined,
    title: data?.title ?? '',
    name: data?.name ?? '',
    des: data?.des ?? '',
    off: data?.off ?? '',
    apr: data?.apr ?? '',
    images: data?.images ?? [],
  };
  state.form = data.post;
  BasicFormApi.setValues({ ...state.form});
  state.pageThemeFiles = data.pageThemeFiles;
}

onMounted(async () => {
  if(index.value>0){
          await onGetPage(index.value);
  }
  
});
</script>

<template>
<Modal :title="state.form.title">
  <Page>
    <Card :title="`${routeTitle} `+$t('page.common.Details')">
      <BasicForm />
    </Card>
  </Page>
</Modal>

</template>
